package com.lq.dao;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//底层dao,与数据库打交道
public class BaseDao {
    //连接数据库
    protected Connection getConn(){
        try {
            //初始化上下文资源，context.xml(这个需要在项目结构配置中设置）
            InitialContext context = new InitialContext();
            //从context中获取name为dataSource/mysql/javawebtest的资源，这里我们本来配置就是DataSource类型，所以可以进行强转，并获取连接进行返回
            DataSource dataSource = (DataSource)context.lookup("java:comp/env/dataSource/mysql/javawebtest");
            return dataSource.getConnection();
        } catch (NamingException |SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    //关闭数据库，三个需要关闭的内容
    protected void closeAll(Connection connection, Statement statement, ResultSet resultSet){

        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
